package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.expandable.ActionSlideExpandableListView;
import cn.com.winning.ecare.utils.DisplayUtil;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.widgets.CustomProgressDialog;
import cn.com.winning.ecare.widgets.InnerListView;

/**
 * 疾病列表
 * @author Administrator
 *
 */
public class Health3 extends Activity
{
	private ActionSlideExpandableListView list_main;
	private InnerListView list_sub;
	private TextView health3_bt; // 标题
	private TextView health3_id; // 症状id
	private ImageButton backButton;

	private Health3 oThis = this;
	private CustomProgressDialog proDialog;// 加载框

	private List<Map<String, Object>> listmain = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> listsub = new ArrayList<Map<String, Object>>();
	private List<Object> children = new ArrayList<Object>();

	private MyMainAdapter mainAdapter = null;
	private MySubAdapter subAdapter = null;
	private int preId = -1;
	private Intent mIntent;
	private String strId;// 症状id
	private String type;// 判断是第几层跳过来的
	private String diseasename = "";// 疾病名称
	private TextView item, content;
	int screenheight;
	int screenwidth;
	private ImageButton mainselected;
	MyApplication myApplication;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.health3_main);
		myApplication = (MyApplication) getApplication();
		myApplication.addActivity(this);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		screenheight = dm.heightPixels;
		screenwidth = dm.widthPixels;
		// 初始化view
		findView();

		// 初始化界面数据
		GetData();

		// 点击事件
		setOnClick();
	}

	// 初始化view
	private void findView()
	{
		list_main = (ActionSlideExpandableListView) findViewById(R.id.hlist);
		health3_bt = (TextView) this.findViewById(R.id.health3_bt);
		health3_id = (TextView) this.findViewById(R.id.health3_id);
		backButton = (ImageButton) this.findViewById(R.id.backButton);
		mIntent = getIntent();
		if (mIntent != null)
		{
			String strMC = mIntent.getStringExtra("mc");
			type = mIntent.getStringExtra("type");
			if (type.equals("Health2"))
			{
				strId = mIntent.getStringExtra("id");
				health3_bt.setText(strMC + "疾病列表");
				health3_id.setText(strId);
			}
			else
			{
				diseasename = mIntent.getStringExtra("diseasename");
				health3_bt.setText("疾病列表");
			}

		}
		
		mainselected = (ImageButton) this.findViewById(R.id.mainselected);

	}

	// 初始化界面数据
	private void GetData()
	{
		proDialog = CustomProgressDialog.createDialog(oThis);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadData()).start();

	}

	class LoadData implements Runnable
	{

		public void run()
		{
			// TODO Auto-generated method stub
			Looper.prepare();
			iniData();
			Looper.loop();
		}
	}

	private void iniData()
	{
		try
		{
			Message msg = myHandler.obtainMessage();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			JSONObject json = null;
			if (type.equals("Health2"))
			{
				ls.add(new BasicNameValuePair("id", strId));
				json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.HEALTHMX, ls);
			}
			else
			{
				ls.add(new BasicNameValuePair("diseasename", diseasename));
				json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.HEALTH1, ls);
			}
			JSONArray jsonArr;
			List<Map<String, Object>> tempmain = new ArrayList<Map<String, Object>>();
			List<Object> tempchildren = new ArrayList<Object>();
			Map<String, Object> tempmap = new HashMap<String, Object>();
			if (json != null)
			{
				if (!json.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
				{
					if (new JSONArray(json.getString("jsonstr")).length() > 0)
					{
						jsonArr = new JSONArray(json.getString("jsonstr"));
						List<Map<String, Object>> list;
						for (int i = 0; i < jsonArr.length(); i++)
						{
							JSONObject obj_main = jsonArr.getJSONObject(i);
							Map<String, Object> map_main = new HashMap<String, Object>();
							map_main.put("mc", obj_main.getString("lbmc"));
							JSONArray js = new JSONArray(obj_main.getString("jbsxmx"));
							list = new ArrayList<Map<String, Object>>();
							for (int j = 0; j < js.length(); j++)
							{
								JSONObject obj_sub = js.getJSONObject(j);
								Map<String, Object> map_sub = new HashMap<String, Object>();
								map_sub.put("sxmc", obj_sub.getString("sxmc"));
								map_sub.put("sxnr", obj_sub.getString("sxnr"));
								list.add(map_sub);
							}

							tempmain.add(map_main);
							tempchildren.add(list);

						}
						msg.what = 0;
						tempmap.put("tempmain", tempmain);
						tempmap.put("tempchildren", tempchildren);
						msg.obj = tempmap;

					}
					else
					{
						msg.what = -1;
						msg.obj = "暂无数据";

					}
				}
				else
				{
					msg.what = -1;
					msg.obj = "系统错误";

				}
			}
			else
			{
				msg.what = -1;
				msg.obj = "网络连接失败!";

			}
			myHandler.sendMessage(msg);
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			Message msg = myHandler.obtainMessage();
			msg.what = -1;
			msg.obj = e.toString();
			myHandler.sendMessage(msg);
		}
	}

	/**
	 * 主线程状态更新
	 */
	Handler myHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case -1:
					proDialog.dismiss();
					Toast.makeText(oThis,  (String) msg.obj, Toast.LENGTH_SHORT).show();
					if (mainAdapter != null)
					{
						mainAdapter.notifyDataSetChanged();
					}
					break;
				case 0:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Map<String, Object> map = (Map<String, Object>) msg.obj;
					listmain = (List<Map<String, Object>>) map.get("tempmain");
					children = (List<Object>) map.get("tempchildren");
					if (mainAdapter == null)
					{
						mainAdapter = new MyMainAdapter();
					}
					list_main.setAdapter(mainAdapter);
					mainAdapter.notifyDataSetChanged();
					break;

				default:
					break;
			}
		};
	};

	// 点击事件
	private void setOnClick()
	{
		backButton.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub

				Health3.this.onBackPressed();

			}
		});
		mainselected.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View view)
			{
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(oThis, Mainmean.class);
				startActivity(intent);
				oThis.finish();
			}
		});

	}

	/**
	 * 自定义listview布局显示内容
	 */
	class MyMainAdapter extends BaseAdapter
	{

		public int getCount()
		{
			// TODO Auto-generated method stub
			return listmain.size();
		}

		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return listmain.get(position);
		}

		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			View view = convertView;
			Map<String, Object> map = (Map<String, Object>) getItem(position);
			view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.health3_sub, null);

			TextView jbmc = (TextView) view.findViewById(R.id.health3_sub_mc);
			jbmc.setText(map.get("mc").toString());

			list_sub = (InnerListView) view.findViewById(R.id.list_jb_sub);
			ScrollView scroll_view = (ScrollView) view.findViewById(R.id.scroll_view);
			listsub = (List<Map<String, Object>>) children.get(position);
			subAdapter = new MySubAdapter(oThis, listsub);
			list_sub.setAdapter(subAdapter);
			list_sub.setParentScrollView(scroll_view);
			list_sub.setMaxHeight(DisplayUtil.dip2px(oThis, 400));
			return view;
		}

	}

	/**
	 * 自定义listview布局显示内容
	 */
	class MySubAdapter extends BaseAdapter
	{

		Context context;
		List children;

		public MySubAdapter(Context context, List children)
		{
			super();
			this.context = context;
			this.children = children;
		}

		public int getCount()
		{
			// TODO Auto-generated method stub
			return children.size();
		}

		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return children.get(position);
		}

		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			View view = convertView;
			Map<String, Object> map = (Map<String, Object>) getItem(position);
			view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.health3_submx, null);

			item = (TextView) view.findViewById(R.id.health3_sx_mc);
			item.setText("[" + map.get("sxmc").toString() + "]");

			content = (TextView) view.findViewById(R.id.health3_sx_nr);
			content.setText(map.get("sxnr").toString());

			return view;
		}

	}

}
